package com.chinawayltd.ews.sample.app;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.manager.openApi.OpenApiManager;
import com.chinawayltd.ews.sample.manager.redis.impl.DriverManagerRedisImpl;
import com.chinawayltd.ews.sample.model.TDriver;
import com.chinawayltd.ews.sample.model.TTask;
import com.chinawayltd.ews.sample.model.TTaskAnomalousEvent;
import com.chinawayltd.ews.sample.model.TTemplateEvent;
import com.chinawayltd.ews.sample.model.openApi.VehicleHistoryDTO;
import com.chinawayltd.ews.sample.model.task.TaskEventVO;
import com.chinawayltd.ews.sample.model.task.TaskListVO;
import com.chinawayltd.ews.sample.service.algorithm.DriverService;
import com.chinawayltd.ews.sample.service.app.AppService;
import com.chinawayltd.ews.sample.service.common.CommonService;
import com.chinawayltd.ews.sample.service.task.TaskEventService;
import com.chinawayltd.ews.sample.service.task.TaskService;
import com.chinawayltd.ews.sample.util.BaseController;
import com.chinawayltd.ews.sample.util.CoordinateUtil;
import com.chinawayltd.ews.sample.util.Gps;
import com.chinawayltd.ews.sample.util.ResultModel;
import com.chinawayltd.ews.sample.util.StringUtils;
import com.chinawayltd.ews.sample.web.query.TaskEventGirdQuery;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: greeProject
 * @description 运输任务管理
 * @author: chenxin
 * @create: 2018年4月17日 下午7:41:00
 */
@Api(tags = { "App任务事件调用接口" })
@RestController
@RequestMapping(value = "/app/event")
public class AppTaskEventController extends BaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private AppService appService;
    @Autowired
    private TaskEventService taskEventService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private DriverManagerRedisImpl driverManagerRedisImpl;
    @Autowired
    private DriverService driverService;
    @Autowired
    private OpenApiManager openApiManager;
    @Autowired
    private TaskService taskService;
    
	@Value("${sys.url}")
	private String sysUrl;
	private String ak = "03d371c5c9927a9522fc046a5ac08ea9";
    private final String DRIVER = "DRIVER:";
    
    @ApiOperation(value = "去异常上报页面需要查询的异常类型接口")
	@RequestMapping(value = "/loadEventListData", method = { RequestMethod.POST })
	@ApiImplicitParams({
			@ApiImplicitParam(name = "vehicleId", value = "任务的车辆id", paramType = "query", dataType = "long",required = true),
			@ApiImplicitParam(name = "eventName", value = "异常名称", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "eventId", value = "异常id", paramType = "query", dataType = "long") })
	public ResultModel loadEventListData(Long vehicleId, String eventName, Long eventId, HttpServletRequest request) {
		ResultModel model = new ResultModel();
		try {
			String token = request.getHeader("token");
        	String keyToken = DRIVER+token;
        	String driverStr = driverManagerRedisImpl.getTokenDriverByKey(keyToken);
        	if(StringUtils.isNotBlank(driverStr)){
        		List<TTemplateEvent> dataList = commonService.loadEventListDataByVid(vehicleId, eventName, eventId);
    			model.setData(new JSONObject().fluentPut("result", dataList));
        	}else{
				model.setSub_code(1);
				model.setData(new JSONObject().fluentPut("sub_msg" , "操作失败,请检查用户是否有效!"));
        	}
		} catch (BusinessException e){
	        model.setSub_code(1);
	        model.setData(new JSONObject().fluentPut("sub_msg" , "查询失败!"));
	    }  catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "查询失败!"));
            model.setSub_msg(e.getMessage());
			logger.error("异常类型接口查询出错！", e);
		}
		return model;
	}
    
	@ApiOperation(value = "异常上报提交接口(异常事件保存)")
	@RequestMapping(value = "/add", method = { RequestMethod.POST })
	public ResultModel addEvent(TTaskAnomalousEvent event, HttpServletRequest request) {
		ResultModel model = new ResultModel();
		try {
			logger.info("经纬度--------------："+event.getLongitude()+" , "+event.getLatitude());
			String token = request.getHeader("token");
        	String keyToken = DRIVER+token;
        	String driverStr = driverManagerRedisImpl.getTokenDriverByKey(keyToken);
        	if(StringUtils.isNotBlank(driverStr)){
        		if(StringUtils.isBlank(event.getEventId().toString())){
    				throw new BusinessException("异常类型不能为空，添加失败");
    			}
        		if(StringUtils.isBlank(event.getTaskId().toString())){
        			throw new BusinessException("任务ID不存在，添加失败");
    			}
        		TTask data = taskService.getTaskById(event.getTaskId());
        		if(data ==null){
        			throw new BusinessException("任务不存在，添加失败");
        		}
        		Gps gps = CoordinateUtil.bdEncrypt(event.getLongitude() ,event.getLatitude());
        	    String addr = appService.getAddrByBaidu(gps.getWgLon()+"",gps.getWgLat()+"", ak);
        		if(addr!=null){
        			event.setEventAddr(addr);
        		}else{
        			throw new BusinessException("无法定位，添加失败！");
        		}
    			int result = appService.addEvent(event);
    			if(result > 0){
    				model.setData(new JSONObject().fluentPut("result" , "添加成功"));
    	        }else{
    	        	model.setSub_code(1);
    	        	model.setData(new JSONObject().fluentPut("sub_msg" , "添加失败"));
    	        }
        	}else{
				model.setSub_code(1);
				model.setData(new JSONObject().fluentPut("sub_msg" , "添加失败"));
        	}
        } catch (BusinessException e){
	        model.setSub_code(1);
	        model.setData(new JSONObject().fluentPut("sub_msg" , e.getMessage()));
	    } catch (Exception e){
        	model.setSub_code(1);
            model.setData(new JSONObject().fluentPut("sub_msg", "无法定位，添加失败！"));
        }
		return model;
	}
	
    @ApiOperation(value = "异常事件列表")
    @RequestMapping(value = "/list", method = { RequestMethod.POST })
    public ResultModel getTaskEventList(TaskEventGirdQuery queryParam, HttpServletRequest request) {
    	ResultModel model = new ResultModel();
        try {
        	String token = request.getHeader("token");
        	String keyToken = DRIVER+token;
        	String driverStr = driverManagerRedisImpl.getTokenDriverByKey(keyToken);
        	Long driverId = null;//获取司机id
        	if(StringUtils.isNotBlank(driverStr)){
            	Map map = (Map)JSON.parse(driverStr);
        		if(map!=null && !map.isEmpty() && map.get("phone") !=null){
        			String phone = map.get("phone").toString();
        			driverId = getDriverByPhone(phone);
        		}else{
        			throw new BusinessException("司机不存在！");
        		}
                List<TaskEventVO> list = null;
            	String sortStr = queryParam.getSortStr();
            	if(StringUtils.isBlank(sortStr)){
            		queryParam.setSortStr("reportTime DESC");
            	}
            	if(driverId !=null){
            		queryParam.setDriverId(driverId.toString());
            		list = taskEventService.getAllTaskEventList(queryParam);
            	}else{
            		list = new ArrayList<>();
            	}
            	queryParam.setDriverId(driverId.toString());
        		list = taskEventService.getAllTaskEventList(queryParam);
        		
                model.setData(new JSONObject().fluentPut("result", list));
                model.setPage(queryParam);
        	}else{
				model.setData(new JSONObject().fluentPut("result", new ArrayList<>()));
        	}

        } catch (BusinessException e){
	        model.setData(new JSONObject().fluentPut("result", new ArrayList<>()));
	    } catch (Exception e){
	        logger.error("异常事件列表查询出错！", e);
	        model.setSub_code(1);
	        model.setData(new JSONObject().fluentPut("sub_msg", "查询失败!"));
	        model.setSub_msg(e.getMessage());
	    }
		return model;
    }
    
    /**
     * 通过司机手机查询司机id
     * @author: chenxin
     * @date: 2018年7月5日 下午12:15:40
     * @param phone
     * @return
     * @throws Exception
     */
	private Long getDriverByPhone(String phone) throws Exception {
		Long driverId = null;
		List<TDriver> driver = driverService.getDriverByPhone(phone);
		if(driver !=null && driver.size() >0){//如果有司机
			TDriver tDriver = driver.get(0);
			driverId = tDriver.getId();
		}else{
			throw new BusinessException("司机不存在！");
		}
		return driverId;
	}
}
